package com.example.piece.tools

import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.os.Build
import android.telephony.SubscriptionManager
import android.telephony.TelephonyManager
import android.text.TextUtils
import android.util.Log
import androidx.annotation.RequiresApi
import androidx.core.content.ContextCompat.getSystemService
import com.example.base.aop.permission.PermissionRequest
import com.example.base.ui.view.broccoli.util.LogUtil
import java.lang.Exception

@RequiresApi(Build.VERSION_CODES.LOLLIPOP_MR1)
class SIMCardInfo(context: Context) {
    private val telephonyManager: TelephonyManager

    private val subscriptionManager: SubscriptionManager
    private var IMSI // 国际移动用户识别码
            : String? = null//返回设备的电话号码

    val phoneNumberS: List<String>
        @SuppressLint("MissingPermission")
        get() {
            //电话号集合
            val locationPhoneHashSet = HashSet<String>()

            var phoneNumber: String? = null
            phoneNumber = telephonyManager.line1Number //返回设备的电话号码

            if (!TextUtils.isEmpty(phoneNumber)) {
                phoneNumber?.let { locationPhoneHashSet.add(it) }
            }


            //根据对象名获取类名

            val name = telephonyManager.javaClass.name
            //根据类名获取类
            val cls: Class<*> = Class.forName(name)
            val method = cls.getDeclaredMethod("getLine1Number", Int::class.javaPrimitiveType)
            method.setAccessible(true);


            val activeSubscriptionInfoList = subscriptionManager.activeSubscriptionInfoList

            if (activeSubscriptionInfoList != null) {
                for (it in activeSubscriptionInfoList) {
                    val phoneNumber = method.invoke(telephonyManager, it.subscriptionId) as String
                    if (!TextUtils.isEmpty(phoneNumber)) {
                        phoneNumber?.let { locationPhoneHashSet.add(it) }
                    }
                }
            }


             return locationPhoneHashSet.toList()

        }
    //获取本机运营商信息// <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
    //使用这个需要在manifest文件里面添加 权限<uses-permission android:name="android.permission.READ_PHONE_STATE" />
    //或者：IMSI=telephonyManager.getSimOperator();
    // IMSI号前面3位460是国家，紧接着后面2位00 02是中国移动，01是中国联通，03是中国电信
    /**
     * 方法一：getSubscriberId()，获取IMSI号
     * 方法二：getSimOperator()获取SIM运营商代码(MCCMNC码)/getSimOperatorName()获取运营商名称（英文）
     * 【getNetworkOperator()获取网络运营商代码/getNetworkOperatorName()获取网络运营商名称（英文）】
     * 网络运营商是网络的运营商。一般SIM运营商和网络运营商是同一个，如用移动的就只能开移动的手机网络。
     * 从卡获取信息有所不同。
     *
     * @return
     */
    val providersName: String?
        get() {
            var ProvidersName: String? = null
            // <p>Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
            IMSI =
                telephonyManager.subscriberId //使用这个需要在manifest文件里面添加 权限<uses-permission android:name="android.permission.READ_PHONE_STATE" />
            //或者：IMSI=telephonyManager.getSimOperator();
            Log.d("TAG", "IMSI== $IMSI")
            // IMSI号前面3位460是国家，紧接着后面2位00 02是中国移动，01是中国联通，03是中国电信
            try {
                if (IMSI?.startsWith("46000") == true || IMSI?.startsWith("46002") == true) {
                    ProvidersName = "中国移动"
                } else if (IMSI?.startsWith("46001") == true) {
                    ProvidersName = "中国联通"
                } else if (IMSI?.startsWith("46003") == true) {
                    ProvidersName = "中国电信"
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
            return ProvidersName
        }//联网才有用

    /**
     * 测试：getSimOperator()获取运营商代码/getSimOperatorName()获取运营商名称
     */
    val operatorName: String
        get() {
            val simOperator = telephonyManager.simOperator
            Log.d("TAG", "SIM运营商代码: --$simOperator")
            val simOperatorName = telephonyManager.simOperatorName
            Log.d("TAG", "SIM运营商:-- $simOperatorName")
            val networkOperator = telephonyManager.networkOperator //联网才有用
            Log.d("TAG", "网络运营商代码:-- $networkOperator")
            val networkOperatorName = telephonyManager.networkOperatorName
            Log.d("TAG", "网络运营商:-- $networkOperatorName")
            return simOperatorName
        }

    init {
        telephonyManager = context
            .getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager

        subscriptionManager =
            context.getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE) as SubscriptionManager
    }
}